package com.terry.activity.bean;

import com.terry.activity.bean.constant.WeChatConstant;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

/**
 * 微信 Js Ticket Config
 *
 * Create On 18/5/7.
 *
 * @author TerrySolar
 */
public class WeChatJsConfig {

    private static Logger logger = Logger.getLogger(WeChatJsConfig.class) ;

    /**
     * 开启调试模式,调用的所有api的返回值会在客户端alert出来，
     * 若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，
     * 仅在pc端时才会打印。
     */
    private Boolean debug = false;

    /** 必填，公众号的唯一标识 */
    private String appId = WeChatConstant.APP_ID;

    /** 必填，生成签名的时间戳 */
    private Long timestamp;

    /** 必填，生成签名的随机串 */
    private String nonceStr;

    /** 必填，签名 */
    private String signature;

    /** 必填，需要使用的JS接口列表 */
    private String[] jsApiList = new String[]{
            "onMenuShareTimeline",
            "onMenuShareAppMessage",
            "hideMenuItems"
    };

    public WeChatJsConfig() {
    }

    public WeChatJsConfig(String jsapi_ticket, String url) {
        this.timestamp = System.currentTimeMillis() / 1000;
        this.nonceStr = RandomStringUtils.randomAlphanumeric(15);
        this.signature = generateSignature(jsapi_ticket, url);
    }

    public Boolean getDebug() {
        return debug;
    }

    public void setDebug(Boolean debug) {
        this.debug = debug;
    }

    public String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        this.appId = appId;
    }

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    public String getNonceStr() {
        return nonceStr;
    }

    public void setNonceStr(String nonceStr) {
        this.nonceStr = nonceStr;
    }

    public String getSignature() {
        return signature;
    }

    public void setSignature(String signature) {
        this.signature = signature;
    }

    public String[] getJsApiList() {
        return jsApiList;
    }

    public void setJsApiList(String[] jsApiList) {
        this.jsApiList = jsApiList;
    }

    /**
     * 生成js签名
     *
     * @return 微信js签名
     */
    private String generateSignature(String jsapi_ticket, String url) {

        String signatureStr = "";

        // 注意这里参数名必须全部小写，且必须有序
        String paras = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + this.nonceStr
                + "&timestamp=" + this.timestamp + "&url=" + url;

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(paras.getBytes("UTF-8"));
            signatureStr = byteToHex(crypt.digest());

        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            logger.error("js签名生成失败", e);
        }

        return signatureStr;
    }

    private String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }
}
